from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import action   #自动生成路由的装饰器
from apps.drf_test_0Django原始restful.models import BookinfoModels
from apps.drf_test_8_ModelViewSet视图.serializer import BookModelSerializer


class BookModelViewSet(ModelViewSet):
    """
    实现列表视图和详情视图
        ModelViewSet 继承自
                   mixins.CreateModelMixin,         creat() --> post()
                   mixins.RetrieveModelMixin,       retrieve() --> get()
                   mixins.UpdateModelMixin,         update() --> put()
                   mixins.DestroyModelMixin,        destroy() --> delete()
                   mixins.ListModelMixin,           list() --> get()
    """

    queryset = BookinfoModels.objects.all()
    serializer_class = BookModelSerializer

    # 获取阅读量大于10的书籍
    @action(methods=["GET"],detail=False)  #添加装饰器，让路由自动生成
    def breadGT10(self,request):
        books = BookinfoModels.objects.filter(bread__gt=10)
        serializer = self.get_serializer(instance=books,many=True)
        return Response(serializer.data,status=status.HTTP_200_OK)

    # 修改id为1的书籍阅读量为99（ 前端只传{bread=99} ） **设置序列化器参数 partial=True 表示部分修改
    @action(methods=['PUT'],detail=True)
    def put_bread(self,request,pk):
        book = self.get_object()
        res = request.data
        serializer = self.get_serializer(instance=book,data=res,partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data,status=status.HTTP_201_CREATED)